#include "imagecontainer.h"
#include "displayitem.h"

namespace Haha
{
class ImageContainerPrivate
{
public:
    ImageContainerPrivate(ImageContainer* q);
    ~ImageContainerPrivate();

    ImageContainer* q_ptr = nullptr;
    QList<DisplayItem*> items;

    void layoutItems();
};

ImageContainerPrivate::ImageContainerPrivate(ImageContainer *q) : q_ptr(q)
{

}

ImageContainerPrivate::~ImageContainerPrivate()
{
    qDeleteAll(items);
}

void ImageContainerPrivate::layoutItems()
{
    int maxWidth = 0;
    int height = 0;
    for (int i = 0; i < items.size(); ++i) {
        DisplayItem* di = items.at(i);

        di->move(0, height);
        if (maxWidth < di->width())
            maxWidth = di->width();
        height += di->height();
        di->show();
    }

    q_ptr->setMinimumSize(maxWidth, height);
}

ImageContainer::ImageContainer(QWidget *parent) : QWidget(parent)
{
    d_ptr = new ImageContainerPrivate(this);
}

ImageContainer::~ImageContainer()
{
    delete d_ptr;
}

void ImageContainer::addItem(DisplayItem* item)
{
    item->setParent(this);
    d_ptr->items.append(item);
    d_ptr->layoutItems();
}

void ImageContainer::clear()
{
    qDeleteAll(d_ptr->items);
    d_ptr->items.clear();
    d_ptr->layoutItems();
}

void ImageContainer::resizeEvent(QResizeEvent *e)
{
    d_ptr->layoutItems();
    QWidget::resizeEvent(e);
}

QSize ImageContainer::sizeHint() const
{
    return QSize(300, 300);
}

} // namespace haha
